package com.atguigu.gulimall.product.service.impl;

import com.atguigu.common.constant.ProductConst;
import com.atguigu.gulimall.product.dao.AttrAttrgroupRelationDao;
import com.atguigu.gulimall.product.dao.AttrGroupDao;
import com.atguigu.gulimall.product.dao.CategoryDao;
import com.atguigu.gulimall.product.entity.AttrAttrgroupRelationEntity;
import com.atguigu.gulimall.product.entity.AttrGroupEntity;
import com.atguigu.gulimall.product.entity.CategoryEntity;
import com.atguigu.gulimall.product.service.AttrAttrgroupRelationService;
import com.atguigu.gulimall.product.service.CategoryService;
import com.atguigu.gulimall.product.vo.AttrGroupRelationVo;
import com.atguigu.gulimall.product.vo.AttrResVo;
import com.atguigu.gulimall.product.vo.AttrVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.product.dao.AttrDao;
import com.atguigu.gulimall.product.entity.AttrEntity;
import com.atguigu.gulimall.product.service.AttrService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {

    @Autowired
    private AttrAttrgroupRelationDao attrAttrgroupRelationDao;


    @Autowired
    private AttrGroupDao attrGroupDao;

    @Autowired
    private CategoryDao categoryDao;

    @Autowired
    private CategoryService categoryService;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void saveAttr(AttrVo attrVo) {

        //保存基本信息
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attrVo, attrEntity);
        this.baseMapper.insert(attrEntity);

        //保存关联信息
        if (attrVo.getAttrType() == ProductConst.AttrEnum.ATTR_TYPR_BASE.getCode() && attrVo.getAttrGroupId() != null) {
            AttrAttrgroupRelationEntity attrgr = new AttrAttrgroupRelationEntity();
            attrgr.setAttrId(attrEntity.getAttrId());
            attrgr.setAttrGroupId(attrVo.getAttrGroupId());
            attrAttrgroupRelationDao.insert(attrgr);
        }
    }

    @Override
    public PageUtils queryCusPage(Map<String, Object> params, Long catelogId, String attrType) {

        QueryWrapper<AttrEntity> attrEntityQueryWrapper = new QueryWrapper<AttrEntity>().eq("attr_type", "base".equalsIgnoreCase(attrType) ? 1 : 0);
        if (catelogId != 0) {
            attrEntityQueryWrapper.eq("catelog_id", catelogId);
        }
        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)) {
            attrEntityQueryWrapper.and(x -> {
                x.eq("attr_id", key).or().like("attr_name", key);
            });
        }
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                attrEntityQueryWrapper
        );
        PageUtils pageUtils = new PageUtils(page);

        List<AttrEntity> records = page.getRecords();
        List<AttrResVo> collect = records.stream().map(x -> {
            AttrResVo attrResVo = new AttrResVo();
            BeanUtils.copyProperties(x, attrResVo);

            //设置分组和分组的名称
            QueryWrapper<AttrAttrgroupRelationEntity> attwrapper = new QueryWrapper<AttrAttrgroupRelationEntity>()
                    .eq("attr_id", x.getAttrId());
            AttrAttrgroupRelationEntity attre = attrAttrgroupRelationDao.selectOne(attwrapper);
            if ("base".equalsIgnoreCase(attrType) && attre != null  &&  attre.getAttrGroupId() != null) {
                if(attre != null ){
                    Long attrGroupId = attre.getAttrGroupId();
                    AttrGroupEntity attrGroupEntity = null;
                    if (attrGroupId != null) {
                        attrGroupEntity = attrGroupDao.selectById(attrGroupId);
                        attrResVo.setGroupName(attrGroupEntity.getAttrGroupName());
                    }
                }
            }

            CategoryEntity categoryEntity = categoryDao.selectById(x.getCatelogId());
            if (categoryEntity != null) {
                attrResVo.setCatelogName(categoryEntity.getName());
            }
            return attrResVo;
        }).collect(Collectors.toList());
        pageUtils.setList(collect);
        return pageUtils;
    }

    @Override
    public AttrResVo getAttrResVo(Long attrId) {
        AttrEntity attrEntity = this.baseMapper.selectById(attrId);
        AttrResVo attrResVo = new AttrResVo();
        BeanUtils.copyProperties(attrEntity, attrResVo);


        AttrAttrgroupRelationEntity attrrelation = attrAttrgroupRelationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>()
                .eq("attr_id", attrId));
        if (attrEntity.getAttrType() == ProductConst.AttrEnum.ATTR_TYPR_BASE.getCode()) {
            if (attrrelation != null) {
                attrResVo.setAttrGroupId(attrrelation.getAttrGroupId());
                AttrGroupEntity attre = attrGroupDao.selectOne(new QueryWrapper<AttrGroupEntity>()
                        .eq("attr_group_id", attrrelation.getAttrGroupId()));
                if (attre != null) {
                    attrResVo.setGroupName(attre.getAttrGroupName());
                }
            }
        }
        Long[] catelogPath = categoryService.findCatelogPath(attrEntity.getCatelogId());
        attrResVo.setCatelogPath(catelogPath);

        CategoryEntity categoryEntity = categoryDao.selectById(attrEntity.getCatelogId());
        if (categoryEntity != null) {
            attrResVo.setAttrName(categoryEntity.getName());
        }
        return attrResVo;

    }


    @Transactional
    @Override
    public void updateAttrVo(AttrVo attr) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr, attrEntity);
        this.baseMapper.updateById(attrEntity);


        if (attr.getAttrType() == ProductConst.AttrEnum.ATTR_TYPR_BASE.getCode()) {
            //修改分组
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            relationEntity.setAttrGroupId(attr.getAttrGroupId());
            relationEntity.setAttrId(attr.getAttrId());

            QueryWrapper<AttrAttrgroupRelationEntity> attrr = new QueryWrapper<>();
            attrr.eq("attr_id", attr.getAttrId());
            Integer integer = attrAttrgroupRelationDao.selectCount(attrr);
            if (integer > 0) {
                attrAttrgroupRelationDao.update(relationEntity, attrr);
            } else {
                attrAttrgroupRelationDao.insert(relationEntity);
            }
        }

    }


    /**
     * Author : hmy
     *
     * @date 2021/6/27 17:33
     * desc :  根据分组id查找关联的所有属性
     **/
    @Override
    public List<AttrEntity> getRelationAttr(Long attrgroupId) {
        List<AttrAttrgroupRelationEntity> attrGroupList = attrAttrgroupRelationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_group_id", attrgroupId));
        if (CollectionUtils.isEmpty(attrGroupList)) {
            return Collections.EMPTY_LIST;
        }
        Set<Long> collect = attrGroupList.stream().map(x -> x.getAttrId()).collect(Collectors.toSet());
        List<AttrEntity> attrEntities = this.baseMapper.selectBatchIds(collect);
        return attrEntities;

    }

    @Override
    public void deleteRelation(List<AttrGroupRelationVo> attrGroupRelationVos) {

        if (CollectionUtils.isEmpty(attrGroupRelationVos)) {
            return;
        }
        attrGroupRelationVos.stream().forEach(x -> {
            Long attrId = x.getAttrId();
            Long attrGroupId = x.getAttrGroupId();
            QueryWrapper<AttrAttrgroupRelationEntity> eq = new QueryWrapper<AttrAttrgroupRelationEntity>()
                    .eq("attr_id", attrId)
                    .eq("attr_group_id", attrGroupId);
            attrAttrgroupRelationDao.delete(eq);
        });
    }


    //获取当前分组没有关联的所有属性
    @Override
    public PageUtils getNoRelationAttr(Map<String, Object> params, Long attrgroupId) {
        //1：当前分组只能关联自己的所有属性
        AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrgroupId);
        //获取当前分类的id
        Long catelogId = attrGroupEntity.getCatelogId();

        //2：当前分组只能关联别的分组没有引用的属性
        //2.1当前分类下的其它分组，
        List<AttrGroupEntity> catelogList = attrGroupDao.selectList(new QueryWrapper<AttrGroupEntity>()
                .eq("catelog_id", catelogId));
        //2.2 这些分组关联的属性
        if(CollectionUtils.isEmpty(catelogList)){
            return null;
        }
        List<Long> collect = catelogList.stream().map(x -> x.getAttrGroupId()).collect(Collectors.toList());

        List<AttrAttrgroupRelationEntity> attrGroupList = attrAttrgroupRelationDao.selectList(
                new QueryWrapper<AttrAttrgroupRelationEntity>().in("attr_group_id", collect)
                );

        List<Long> attrIdList = attrGroupList.stream().map(x -> x.getAttrId()).collect(Collectors.toList());
        //2.3当前分类的所有属性中移除这个属性
        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<AttrEntity>().eq("catelog_id", catelogId).eq("attr_type",ProductConst.AttrEnum.ATTR_TYPR_BASE.getCode());
        if(!CollectionUtils.isEmpty(attrIdList)){
            wrapper.notIn("attr_id", attrIdList);
        }

        String key = (String) params.get("key");
        if(StringUtils.isEmpty(key)){
            wrapper.and( x ->{
                x.eq("attr_id",key).or().like("attr_name",key);
            });
        }
        IPage<AttrEntity> page = this.page(new Query<AttrEntity>().getPage(params), wrapper);
        PageUtils pageUtils = new PageUtils(page);
        return pageUtils;


    }

    @Override
    public List<Long> selectSeatchAttrIds(List<Long> attrids) {

        return baseMapper.selectSearchAttrIds(attrids);
    }

}
